﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;

namespace QuanLyKTX
{
    using Telerik.WinControls;
    using Telerik.WinControls.UI;
    using DAL;
    public partial class frm_PriceConfig : Telerik.WinControls.UI.RadForm
    {
        #region Fields
        bool update = false;
        DateTime ngayCauHinh;
        RadContextMenu contextMenu;
        #endregion

        #region Private Methods

        private void BindDropDownLoaiHopDong()
        {
            using (var db = new QuanLyKTXDataContext())
            {
                var results = from p in db.tbl_LoaiHopDongs
                              select p;

                radDropDownList_LoaiHopDong.ValueMember = "MaLoaiHD";
                radDropDownList_LoaiHopDong.DisplayMember = "TenLoaiHD";
                radDropDownList_LoaiHopDong.ListElement.Font = new Font("Segoe UI", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
                radDropDownList_LoaiHopDong.ListElement.ItemHeight = 28;
                radDropDownList_LoaiHopDong.DataSource = results;
            }
        }

        // Insert
        /// <summary>
        /// 
        /// </summary>
        /// <param name="maLoaiHD"></param>
        /// <param name="donGiaDien"></param>
        /// <param name="donGiaNuoc"></param>
        /// <param name="phiBanDauVL"></param>
        /// <param name="tienPhongVL"></param>
        /// <param name="phiBanDau"></param>
        /// <param name="tienPhong"></param>
        /// <param name="ngayApDung"></param>
        /// <returns></returns>
        private bool InsHopDongConfig(byte maLoaiHD, decimal donGiaDien, decimal donGiaNuoc, decimal phiBanDauVL, decimal tienPhongVL, decimal phiBanDau, decimal tienPhong, DateTime ngayApDung)
        {
            using (var db = new QuanLyKTXDataContext())
            {
                try
                {
                    MessageBox.Show(db.GetSystemDate().FirstOrDefault().Column1.ToShortDateString());
                    DateTime ngayCauHinh = db.GetSystemDate().FirstOrDefault().Column1;
                    tbl_CauHinhApDungPhi phiApDung = new tbl_CauHinhApDungPhi { NgayCauHinh = ngayCauHinh , MaLoaiHD = maLoaiHD, DonGiaDien = donGiaDien, DonGiaNuoc = donGiaNuoc, PhiBanDauVL = phiBanDauVL, TienPhongVL = tienPhongVL, PhiBanDau = phiBanDau, TienPhong = tienPhong, NgayApDung = ngayApDung, KichHoat = true };

                    var results = from p in db.tbl_CauHinhApDungPhis
                                  where p.NgayCauHinh.Date == ngayCauHinh.Date && p.MaLoaiHD == phiApDung.MaLoaiHD
                                  select p;
                    if (results.Count() == 0)
                    {                        
                        db.tbl_CauHinhApDungPhis.InsertOnSubmit(phiApDung);
                        db.SubmitChanges();

                        var result = (from p in db.tbl_CauHinhApDungPhis
                                      where p.KichHoat == true && p.MaLoaiHD == maLoaiHD && p.NgayCauHinh.Date != ngayCauHinh.Date
                                      select p).Single();
                        result.KichHoat = false;
                        db.SubmitChanges();
                        return true;
                    }
                    else
                    {
                        MessageBox.Show("Không thể thêm vì thông tin đã có sẵn.");                        
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);                    
                    return false;
                }
            }
        }

        // Update
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ngayCauhinh"></param>
        /// <param name="maLoaiHD"></param>
        /// <param name="donGiaDien"></param>
        /// <param name="donGiaNuoc"></param>
        /// <param name="phiBanDauVL"></param>
        /// <param name="tienPhongVL"></param>
        /// <param name="phiBanDau"></param>
        /// <param name="tienPhong"></param>
        /// <param name="ngayApDung"></param>
        /// <returns></returns>
        private bool UpdHopDongConfig(DateTime ngayCauhinh, byte maLoaiHD, decimal donGiaDien, decimal donGiaNuoc, decimal phiBanDauVL, decimal tienPhongVL, decimal phiBanDau, decimal tienPhong, DateTime ngayApDung)
        {
            using (var db=new QuanLyKTXDataContext())
                try
                {
                    var result = (from p in db.tbl_CauHinhApDungPhis
                                  where p.NgayCauHinh.Date == ngayCauhinh.Date && p.MaLoaiHD == maLoaiHD
                                  select p).Single();
                    result.DonGiaDien = donGiaDien;
                    result.DonGiaNuoc = donGiaNuoc;
                    result.PhiBanDauVL = phiBanDauVL;
                    result.TienPhongVL = tienPhongVL;
                    result.PhiBanDau = phiBanDau;
                    result.TienPhong = tienPhong;
                    result.NgayApDung = ngayApDung;

                    db.SubmitChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
        }

        // reset form
        private void ResetFormInput()
        {
            radMaskedEditBox_DGDien.Value = 0;
            radMaskedEditBox_DGDien.Text = "0 ₫";
            radMaskedEditBox_DGNuoc.Value = 0;
            radMaskedEditBox_DGNuoc.Text = "0 ₫";
            radMaskedEditBox_PhiBanDauVL.Value = 0;
            radMaskedEditBox_PhiBanDauVL.Text = "0 ₫";
            radMaskedEditBox_TienPhongVL.Value = 0;
            radMaskedEditBox_TienPhongVL.Text = "0 ₫";
            radMaskedEditBox_PhiBanDau.Value = 0;
            radMaskedEditBox_PhiBanDau.Text = "0 ₫";
            radMaskedEditBox_TienPhong.Value = 0;
            radMaskedEditBox_TienPhong.Text = "0 ₫";
            update = false;
            radDropDownList_LoaiHopDong.Enabled = !update;
            radButton_BoQua.Visible = update;
            radDropDownList_LoaiHopDong.Focus();
        }

        // Bind GridView
        private void BindGridQuyDinh()
        {
            //radGridView_QuyDinh.AutoGenerateColumns = false;

            using (var db = new QuanLyKTXDataContext())
            {
                var results = from p in db.tbl_CauHinhApDungPhis
                              join q in db.tbl_LoaiHopDongs on p.MaLoaiHD equals q.MaLoaiHD
                              orderby p.NgayApDung descending
                              select new
                              {
                                  p.NgayCauHinh,
                                  p.MaLoaiHD,
                                  q.TenLoaiHD,
                                  p.DonGiaDien,
                                  p.DonGiaNuoc,
                                  p.PhiBanDau,
                                  p.PhiBanDauVL,
                                  p.TienPhong,
                                  p.TienPhongVL,
                                  p.NgayApDung,
                                  p.KichHoat
                              };

                radGridView_QuyDinh.DataSource = results;
                radGridView_QuyDinh.ShowGroupPanel = false;
            }
        }

        // Init MenuContext
        private void InitMenuContext()
        {
            contextMenu = new RadContextMenu();
            RadMenuItem editMenu = new RadMenuItem("Sửa");
            editMenu.Click += new EventHandler(editMenu_Click);
            RadMenuItem delMenu = new RadMenuItem("Xóa");
            delMenu.Click += new EventHandler(delMenu_Click);

            contextMenu.Items.Add(editMenu);
            contextMenu.Items.Add(delMenu);
        }
        #endregion

        #region Event Methods

        private void radButton_BoQua_Click(object sender, EventArgs e)
        {
            ResetFormInput();
        }

        private void radGridView_QuyDinh_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
        {
            if (!radGridView_QuyDinh.CurrentRow.IsSystem)
            {
                e.ContextMenu = contextMenu.DropDown;
            }
        }

        private void radButton_Luu_Click(object sender, EventArgs e)
        {
            byte maLoaiHD = Convert.ToByte(radDropDownList_LoaiHopDong.SelectedValue);
            decimal donGiaDien = Convert.ToDecimal(radMaskedEditBox_DGDien.Value);
            decimal donGiaNuoc = Convert.ToDecimal(radMaskedEditBox_DGNuoc.Value);
            decimal phiBanDau = Convert.ToDecimal(radMaskedEditBox_PhiBanDau.Value);
            decimal phiBanDauVL = Convert.ToDecimal(radMaskedEditBox_PhiBanDauVL.Value);
            decimal tienPhong = Convert.ToDecimal(radMaskedEditBox_TienPhong.Value);
            decimal tienPhongVL = Convert.ToDecimal(radMaskedEditBox_TienPhongVL.Value);
            DateTime ngayApDung = radDateTimePicker_NgayApDung.Value.Date;            

            if (update)
            {
                bool updResult = UpdHopDongConfig(ngayCauHinh, maLoaiHD, donGiaDien, donGiaNuoc, phiBanDauVL, tienPhongVL, phiBanDau, tienPhong, ngayApDung);

                if (updResult)
                {
                    BindGridQuyDinh();
                    ResetFormInput();
                }
                else
                {
                    MessageBox.Show("Cập nhật dữ liệu không thành công.");
                }
            }
            else
            {
                bool insResult = InsHopDongConfig(maLoaiHD, donGiaDien, donGiaNuoc, phiBanDauVL, tienPhongVL, phiBanDau, tienPhong, ngayApDung);
                if (insResult)
                {
                    BindGridQuyDinh();
                    ResetFormInput();
                }                
            }

        }

        void delMenu_Click(object sender, EventArgs e)
        {
            DialogResult dlgResult = MessageBox.Show("Bạn có chắc muốn xóa nội dung này", "Cảnh báo", MessageBoxButtons.YesNo);

            if (dlgResult == System.Windows.Forms.DialogResult.Yes)
            {
                using (var db = new QuanLyKTXDataContext())
                {
                    var result = (from p in db.tbl_CauHinhApDungPhis
                                  where p.NgayCauHinh.Date == Convert.ToDateTime(radGridView_QuyDinh.CurrentRow.Cells[0].Value).Date && p.KichHoat == false
                                  select p).FirstOrDefault();
                    if (result != null)
                    {
                        db.tbl_CauHinhApDungPhis.DeleteOnSubmit(result);
                        db.SubmitChanges();

                        BindGridQuyDinh();
                    }
                    else
                    {
                        MessageBox.Show("Nội dung đang được sử dụng. Không thể xóa");
                    }
                }
            }
        }

        void editMenu_Click(object sender, EventArgs e)
        {
            update = true;
            radButton_BoQua.Visible = update;
            ngayCauHinh = Convert.ToDateTime(radGridView_QuyDinh.CurrentRow.Cells[0].Value);
            radDropDownList_LoaiHopDong.SelectedValue = radGridView_QuyDinh.CurrentRow.Cells[2].Value;
            radDropDownList_LoaiHopDong.Enabled = false;
            radMaskedEditBox_DGDien.Value = radGridView_QuyDinh.CurrentRow.Cells[3].Value.ToString();
            radMaskedEditBox_DGNuoc.Value = radGridView_QuyDinh.CurrentRow.Cells[4].Value.ToString();
            radMaskedEditBox_PhiBanDauVL.Value = radGridView_QuyDinh.CurrentRow.Cells[5].Value.ToString();
            radMaskedEditBox_TienPhongVL.Value = radGridView_QuyDinh.CurrentRow.Cells[6].Value.ToString();
            radMaskedEditBox_PhiBanDau.Value = radGridView_QuyDinh.CurrentRow.Cells[7].Value.ToString();
            radMaskedEditBox_TienPhong.Value = radGridView_QuyDinh.CurrentRow.Cells[8].Value.ToString();
            radDateTimePicker_NgayApDung.Value = Convert.ToDateTime(radGridView_QuyDinh.CurrentRow.Cells[9].Value);
            radMaskedEditBox_DGDien.Focus();
        }

        private void radDropDownList_LoaiHopDong_Leave(object sender, EventArgs e)
        {
            ((Telerik.WinControls.UI.RadDropDownListEditableAreaElement)(this.radDropDownList_LoaiHopDong.GetChildAt(0).GetChildAt(0))).BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
        }

        private void radDropDownList_LoaiHopDong_Enter(object sender, EventArgs e)
        {
            ((Telerik.WinControls.UI.RadDropDownListEditableAreaElement)(this.radDropDownList_LoaiHopDong.GetChildAt(0).GetChildAt(0))).BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(253)))), ((int)(((byte)(215)))));
        }

        private void frm_PriceConfig_Load(object sender, EventArgs e)
        {

            BindDropDownLoaiHopDong();

            // show - hidden button Bo qua
            radButton_BoQua.Visible = update;

            // init date Ngay ap dung
            radDateTimePicker_NgayApDung.Value = DateTime.Now;

            BindGridQuyDinh();

            InitMenuContext();
        }

        public frm_PriceConfig()
        {
            InitializeComponent();
        }

        #endregion
    }
}
